package org.rms.cayenne.access;

import java.util.Collection;

import javax.servlet.http.HttpServletRequest;

import org.apache.cayenne.ObjectContext;
import org.apache.cayenne.access.DataContext;
import org.rms.model.access.Persistable;
import org.rms.model.access.Session;

public class CayenneSession implements Session {

    private ObjectContext context;

    public CayenneSession(ObjectContext context) {
        this.context = context;
    }

    public void commitChanges() {
        this.context.commitChanges();
    }

    public void rollbackChanges() {
        this.context.rollbackChanges();
    }

    public static final CayenneSession getSession(HttpServletRequest request) {
        ObjectContext context = (ObjectContext) request.getAttribute(ObjectContext.class.getName());
        if (context == null) {
            context = DataContext.createDataContext();
            request.setAttribute(ObjectContext.class.getName(), context);
        }
        return new CayenneSession(context);
    }

    public ObjectContext getObjectContext() {
        return this.context;
    }

    public void removeFromCache(Collection<Persistable> persistables) {
        ((DataContext) this.context).invalidateObjects(persistables);
    }

}
